package com.synnex.mobile.servier.web.user.controller;

import com.synnex.mobile.generic.core.exception.SystemException;
import com.synnex.mobile.generic.log.dao.annotation.LogClass;
import com.synnex.mobile.generic.web.anotation.mapping.RequestMapping;
import com.synnex.mobile.generic.web.session.WebSession;
import com.synnex.mobile.generic.web.validator.BindException;
import com.synnex.mobile.generic.web.view.JspView;
import com.synnex.mobile.generic.web.view.ModelAndView;
import com.synnex.mobile.generic.web.view.RedirectView;
import com.synnex.mobile.servier.web.common.controller.AbstractController;
import com.synnex.mobile.servier.web.common.session.admin.AdminSession;
import com.synnex.mobile.servier.web.user.exception.PasswordErrorException;
import com.synnex.mobile.servier.web.user.form.LoginForm;
import com.synnex.spy.common.UserNotFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: kerryf
 * Date: 13-7-25
 * To change this template use File | Settings | File Templates.
 */
@RequestMapping(url="/admin")
@LogClass(name="user login")
public class UserController extends AbstractController {

    @RequestMapping(url="/login.do")
    public ModelAndView login(HttpServletRequest request,HttpServletResponse response){

    return new ModelAndView();
    }


    @RequestMapping(url="/loginAction.do", formCommand = "login")
    public ModelAndView loginAction(HttpServletRequest request,HttpServletResponse response,LoginForm form,BindException errors){

        try{
            if(!form.getUser().equals("admin")){
                throw  new UserNotFoundException();
            }
            if(!form.getPassword().equals("servier")){
                throw  new PasswordErrorException();
            }
            this.getAdminSession(request).setUser(form.getUser());
            this.getAdminSession(request).setPassword(form.getPassword());
            return new ModelAndView();
        }catch (UserNotFoundException ex){
            errors.addError("user","用户名错误！");
            throw errors;
        }catch (PasswordErrorException ex){
            errors.addError("password","密码错误！");
            throw errors;
        }
      }


    @RequestMapping(url="/logout.do")
    public ModelAndView logout(HttpServletRequest request,HttpServletResponse response){

        try{
            WebSession.destroySession(AdminSession.class, request);
            return new ModelAndView(new RedirectView("/admin/login.do"));
        }catch (Exception e){
            throw new SystemException(e.getMessage());
        }
    }


}
